package study.source.common.util;

import java.util.Date;
import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GmailSmtpSender {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public static final String DEFAULT_TRANSPORT_PROTOCOLC = "smtp";
	public static String DEFAULT_SMTP_SOCKET_FACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";
	public static String DEFAULT_SMTP_HOST = "smtp.gmail.com";
	public static int DEFAULT_SMTP_PORT = 587;
	public String authId = "special9486@gmail.com";
	public String authPasswd = "chsh7881";
	
	private Properties prop = null;
	
	public GmailSmtpSender(){
		this(DEFAULT_SMTP_HOST, DEFAULT_SMTP_PORT, DEFAULT_SMTP_SOCKET_FACTORY_CLASS);
	}
	
	public GmailSmtpSender(String host, int port, String socketFactory){
		prop = new Properties();
		
		prop.put("mail.smtp.host", host);
		prop.put("mail.smtp.port", String.valueOf(port));
		prop.put("mail.transport.protocol", DEFAULT_TRANSPORT_PROTOCOLC);
		
		prop.put("mail.smtp.auth", "true");
		prop.put("mail.smtp.starttls.enable", "true");
		prop.put("mail.smtp.socketFactory.class", socketFactory);
		
	}
	
	public void sendStmpMail(Map param) throws Exception{
		Message msg = createMessage(param.get("from").toString(), param.get("to").toString());
		
		msg.setSubject(param.get("subject").toString());
		msg.setContent(param.get("content"), "text/html;charset=utf-8");
		msg.setSentDate(new Date());
		
		Transport.send(msg);
		
	}

	private Message createMessage(String from, String to) throws Exception{
		
		GmailSmtpAuthenticator auth = new GmailSmtpAuthenticator(authId, authPasswd); 
		
		Session mailSession = Session.getDefaultInstance(prop, auth);
		
		Message msg = new MimeMessage(mailSession);
		
		msg.setFrom(new InternetAddress(from));
		InternetAddress toAddr = new InternetAddress(to);
		
		msg.setRecipient(Message.RecipientType.TO, toAddr);
		
		return msg;
	}
	
}
